﻿using DesktopShortcutMonitor.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesktopShortcutMonitor.Monitor
{
    public class MonitorFile
    {
        #region 桌面扫描
        /// <summary>
        /// 扫描桌面可执行文件
        /// </summary>
        /// <param name="desktopPath">桌面路径</param>
        /// <returns>找到的可执行文件信息列表</returns>
        public  List<ExeFileInfo> ScanDesktopExecutables(string desktopPath)
        {
            var results = new List<ExeFileInfo>();

            // 配置搜索参数（不包含链接文件）
            //var searchOption = SearchOption.TopDirectoryOnly;
            //var searchPattern = "*.exe";
            //var allFilePath = Directory.EnumerateFiles(desktopPath, searchPattern, searchOption);
            var allFilePath = Directory.EnumerateFiles(desktopPath, "*.*", SearchOption.TopDirectoryOnly)
                    .Where(f => f.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ||
                               f.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase));
            //var allFilePath0 = Directory.EnumerateDirectories(desktopPath);
            //var files = Directory.EnumerateFiles(desktopPath, "*.*", SearchOption.TopDirectoryOnly)
            //        .Where(f => f.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ||
            //                   f.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase));
            foreach (string filePath in allFilePath)
            {
                try
                {
                    // 处理快捷方式
                    if (Path.GetExtension(filePath).Equals(".lnk", StringComparison.OrdinalIgnoreCase))
                    {
                        var target = ResolveShortcut(filePath);
                        if (!string.IsNullOrEmpty(target) && target.EndsWith(".exe"))
                        {
                            var info = ProcessExeFile(target);
                            results.Add(info);
                        }
                        continue;
                    }

                    // 处理直接EXE文件
                    var exeInfo = ProcessExeFile(filePath);
                    results.Add(exeInfo);
                }
                catch { /* 忽略错误文件 */ }
            }
            return results.OrderBy(f => f.FileName).ToList();
        }

        private  ExeFileInfo ProcessExeFile(string filePath)
        {
            var fileInfo = new FileInfo(filePath);
            var versionInfo = FileVersionInfo.GetVersionInfo(filePath);

            return new ExeFileInfo
            {
                FileName = Path.GetFileName(filePath),
                FullPath = filePath,
                FileSize = fileInfo.Length,
                CompanyName = versionInfo.CompanyName,
                ProductVersion = versionInfo.ProductVersion,
                MD5Hash = ComputeFileHash(filePath)
            };
        }

        /// <summary>
        /// 计算文件哈希（MD5）
        /// </summary>
        private  string ComputeFileHash(string filePath)
        {
            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                using (var stream = System.IO.File.OpenRead(filePath))
                {
                    byte[] hash = md5.ComputeHash(stream);
                    return BitConverter.ToString(hash).Replace("-", "");
                }
            }
        }

        // 获取MD5前6位
        private  string GetMd5Short(string filePath)
        {
            try
            {
                using (var md5 = System.Security.Cryptography.MD5.Create())
                {
                    using (var stream = System.IO.File.OpenRead(filePath))
                    {
                        byte[] hash = md5.ComputeHash(stream);
                        return BitConverter.ToString(hash, 0, 3).Replace("-", "");
                    }
                }
            }
            catch { return "N/A"; }
        }

        // 解析快捷方式
        private  string ResolveShortcut(string shortcutPath)
        {
            try
            {
                var shell = new IWshRuntimeLibrary.WshShell();
                var shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);
                return shortcut.TargetPath;
            }
            catch { return null; }
        }


        #endregion

  
    }
}
